<template>
  <basic-container>
    <el-alert v-if="alertBox" style="margin-bottom: 15px" type="error">
      <template slot="title">
        <div class="iconSize">信息提示:</div>
        <div class="iconSize" v-for="(item,index) in errorMsgList">{{index}}.{{item}}</div>
      </template>
    </el-alert>
    <!--附件信息展示-->
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <!--附件上传按钮-->
      <template slot="menuLeft" slot-scope="scope">
        <el-button size="small" type="primary" plain icon="el-icon-upload2" @click="handleUpload">上传附件</el-button>
        <el-button size="small" type="info" plain icon="el-icon-position" @click="handleApprove">提交审批</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menu" slot-scope="scope">
        <el-button icon="el-icon-view" size="small" type="text" @click.stop="viewBtn(scope.row)">查 看</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="editExcel(scope.row)">修改附件</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" @click.stop="rowDel(scope.row)">删 除</el-button>
      </template>
    </avue-crud>

    <!--上传附件模态窗口信息-->
    <div v-if="attachBox">
      <el-dialog title="附件上传" append-to-body center :visible.sync="attachBox" width="35%" :close-on-click-modal='false'>
        <el-scrollbar style="height:500px;" v-loading="loading">
          <el-form ref="attachFormRef" :model="attachForm" label-width="80px" size="small" :rules="ruleForm">
            <el-form-item label="图纸编号" prop="drawingNumber">
              <el-input v-model="attachForm.drawingNumber" @change="drawingNumberChange" prefix-icon="el-icon-coin">
              </el-input>
            </el-form-item>
            <el-form-item label="图纸名称" prop="drawingName">
              <el-input v-model="attachForm.drawingName" prefix-icon="el-icon-coin"></el-input>
            </el-form-item>
            <el-form-item label="设备材料" prop="material">
              <el-input v-model="attachForm.material" prefix-icon="el-icon-coin"></el-input>
            </el-form-item>
            <el-form-item label="产品父类" prop="productParentIdName">
              <el-input v-model="attachForm.productParentIdName" :readonly="true" prefix-icon="el-icon-coin"></el-input>
            </el-form-item>
            <el-form-item label="产品大类" prop="productChildIdName">
              <el-input v-model="attachForm.productChildIdName" :readonly="true" prefix-icon="el-icon-coin"></el-input>
            </el-form-item>
            <el-form-item label="图纸类别" prop="drawingCategoryName">
              <el-input v-model="attachForm.drawingCategoryName" :readonly="true" prefix-icon="el-icon-coin"></el-input>
            </el-form-item>
            <el-alert style="margin-bottom: 15px" type="error" v-if="errorBox" :closable="false">
              <template slot="title">
                <div class="iconSize">信息提示:</div>
                <div class="iconSize" v-for="(item,index) in errorList">({{index+1}}){{item}}</div>
              </template>
            </el-alert>
            <el-form-item label="附件上传" prop="attchFiles">
              <el-upload class="avatar-uploader" action="#" drag="true" ref="fileUpload" 
                :auto-upload="false"
                :multiple="true" 
                accept=".xls,.xlsx,.pdf,.dwg,.PDF,.DWG" 
                :file-list="fileList"
                :before-upload="uploadBefore" :on-change="uploadChange" :on-success="handleSuccess"
                :on-preview="handlePreview" :http-request="beforeUpload">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 xls/xlsx/pdf/dwg格式得文件</div>
                </template>
              </el-upload>
            </el-form-item>
           
            <el-form-item label="三维图纸" prop="threeFiles" ref="threeElement">
              <el-upload class="avatar-uploader" action="#" drag ref="threeUpload" :auto-upload="false"
                :multiple="false" accept=".zip,.rar" :file-list="threeFileList" :on-preview="handlePreview"
                :http-request="threrBeforeUpload">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 三维图格式得文件</div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="图纸截图" prop="imgFiles" ref="imgElement">
              <el-upload style="display: inline-block;" class="avatar-uploader" action="#" ref="imgUpload" drag list-type="picture" :auto-upload="false" :multiple="true"
                accept=".png,.jpg,.jpeg,.gif" :on-preview="handlePictureCardPreview" :http-request="imgBeforeUpload"
                :on-remove="handleRemove">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将图纸截图拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 png/jpg/jpeg/gif格式得文件</div>
                </template>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" append-to-body>
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-form>
        </el-scrollbar>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitAttach('attachFormRef')" size="small" :loading="btnLoading" icon="el-icon-check">提 交
            </el-button>
            <el-button @click="attachBox = false" size="small" icon="el-icon-close">取 消</el-button>
          </span>
        </template>

      </el-dialog>
    </div>

    <!--查看信息-->
    <div v-if="viewBox">
      <el-dialog title="信息查看" append-to-body center :visible.sync="viewBox" width="35%" :close-on-click-modal='false'>
        <el-scrollbar style="height:500px;">
          <el-form ref="attachFormRef" :model="attachForm" label-width="80px" size="small" :rules="ruleForm">
            <el-form-item label="图纸编号" prop="drawingNumber">
              <el-input v-model="attachForm.drawingNumber" disabled></el-input>
            </el-form-item>
            <el-form-item label="图纸名称" prop="drawingName">
              <el-input v-model="attachForm.drawingName" disabled></el-input>
            </el-form-item>
            <el-form-item label="设备材料" prop="material">
              <el-input v-model="attachForm.material"></el-input>
            </el-form-item>
            <el-form-item label="附件上传" prop="attchFiles">
              <el-upload disabled class="avatar-uploader" action="#" :auto-upload="false" :file-list="fileList"
                :on-preview="handlePreview" :http-request="beforeUpload">
                <i class="el-icon-upload"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="三维图纸" prop="threeFiles" ref="threeElement">
              <el-upload class="avatar-uploader" action="#" disabled accept=".zip,.rar" :auto-upload="false"
                :multiple="false" :file-list="threeFileList" :on-preview="handlePreview"
                :http-request="threrBeforeUpload">
              </el-upload>
            </el-form-item>
            <el-form-item label="图纸截图" prop="imgFiles" ref="imgElement">
              <el-upload class="avatar-uploader" action="#" ref="imgUpload"
                :multiple="true" list-type="picture" disabled :auto-upload="false" :file-list="imgFileList"
                :on-preview="handlePictureCardPreview">
                <!-- <i class="el-icon-plus"></i>
                <template #tip>
                  <div class="el-upload__tip">只能上传 png/jpg/jpeg/gif格式得文件</div>
                </template> -->
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" append-to-body>
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-form>
        </el-scrollbar>

      </el-dialog>

    </div>

    <!--修改附件-->
    <div v-if="editBox">
      <el-dialog title="修改附件信息" append-to-body center :visible.sync="editBox" width="35%" :close-on-click-modal='false'>
        <el-scrollbar style="height:500px;"  v-loading="loading">
          <el-form ref="editFormRef" :model="attachForm" label-width="80px" size="small" :rules="editRuleForm">
            <el-form-item label="图纸编号" prop="drawingNumber">
              <el-input v-model="attachForm.drawingNumber" :readonly="true"></el-input>
            </el-form-item>
            <el-form-item label="图纸名称" prop="drawingName">
              <el-input v-model="attachForm.drawingName" :readonly="true"></el-input>
            </el-form-item>
            <el-form-item label="设备材料" prop="material">
              <el-input v-model="attachForm.material"></el-input>
            </el-form-item>
            <el-alert style="margin-bottom: 15px" type="error" v-if="errorBox" :closable="false">
              <template slot="title">
                <div class="iconSize">信息提示:</div>
                <div class="iconSize" v-for="(item,index) in errorList">({{index+1}}){{item}}</div>
              </template>
            </el-alert>
            <!--二维图纸-->
            <el-form-item label="附件上传" prop="editAttchFiles">
              <el-upload class="avatar-uploader" action="#" drag="true" ref="editFileUpload" :auto-upload="false"
                :multiple="true" accept=".xls,.xlsx,.pdf,.dwg,.PDF,.DWG" :file-list="fileList" :on-change="uploadChange"
                :on-preview="handlePreview" :on-success="editSuccess" :before-remove="editRemove"
                :http-request="editHttpRequest">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 xls/xlsx/pdf/dwg格式得文件</div>
                </template>
              </el-upload>
            </el-form-item>
           
            <!--三维图纸-->
            <el-form-item label="三维图纸" prop="threeFiles">
              <el-upload class="avatar-uploader" action="#" drag="true" accept=".zip,.rar" name="editThreeUpload"
                ref="editThreeUpload" :auto-upload="false" :multiple="true" :file-list="threeFileList"
                :on-preview="handlePreview" :http-request="threrBeforeUpload" :before-remove="editRemoveThree">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 三维图格式得文件</div>
                </template>
              </el-upload>
            </el-form-item>
            <!--图纸截图-->
            <el-form-item label="图纸截图" prop="imgFiles" ref="imgElement">
              <el-upload style="display: inline-block" class="avatar-uploader" action="#" ref="editImgUpload"
                list-type="picture" drag :auto-upload="false" :multiple="true" :file-list="imgFileList"
                :http-request="imgBeforeUpload" accept=".png,.jpg,.jpeg,.gif" 
                :on-preview="handlePictureCardPreview" :before-remove="editRemoveImg">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将图纸截图拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 png/jpg/jpeg/gif格式得文件</div>
                </template>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" append-to-body>
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-form>
        </el-scrollbar>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="editAttach('editFormRef')" size="small" :loading="btnLoading" icon="el-icon-check">提 交
            </el-button>
            <el-button @click="editBox = false" size="small" icon="el-icon-close">取 消</el-button>
          </span>
        </template>


      </el-dialog>
    </div>


  </basic-container>
</template>

<script>
  import {
    getList, getDetail, add, update, remove, getPdfByUploadId,
    getThreeByUploadId,getApplicationByNumber, changeUploadStatus, getOrderAllList, getProjectById, getImgListByUploadId
  }
    from "@/api/drawing/drawingupload";
  import { mapGetters } from "vuex";
import uploadfile from './uploadfile.vue';
  export default {
  components: { uploadfile },
    name: "drawingupload",
    data() {
      // 上传附件验证
      let checkAttachFiles = (rule, value, callback) => {
        if (!this.$refs.fileUpload.uploadFiles.length) {
          callback(new Error('请选择要上传的文件'));
        } else {
          callback();
        }
      };
      // 修改时验证规则
      let editAttachFiles = (rule, value, callback) => {
        if (!this.$refs.editFileUpload.uploadFiles.length) {
          callback(new Error('请选择要上传的文件'));
        } else {
          callback();
        }
      };

      return {
        // 工单号数组
        orderList: [],
        changeFlag: false,
        // 修改图纸
        editBox: false,
        // 修改时验证规则
        editRuleForm: {
          drawingNumber: [
            { required: true, message: '请输入图纸代码', trigger: 'blur' },
          ],
          drawingName: [
            { required: true, message: '请输入图纸名称', trigger: 'blur' },
          ],
          editAttchFiles: [
            { validator: editAttachFiles, required: true },
          ],
          projectId: [
            { required: true, message: '请选择工单号', trigger: 'change' },
          ],
          customerName: [
            { required: true, message: '请选择客户名称', trigger: 'change' },
          ],
          projectName: [
            { required: true, message: '请选择项目名称', trigger: 'change' },
          ],

        },
        fileType: ['xls', 'xlsx', 'pdf', 'PDF', 'dwg', 'DWG'],
        // 查看
        viewBox: false,
        uploadForm: new FormData(),
        // 上传附件模态窗口
        attachBox: false,
        btnLoading: false,
        errorBox: false,
        errorList: [],
        // 附件上传列表
        attachForm: {
          id: '',
          drawingNumber: '',
          drawingName: '',
          attchFiles: '',
          threeFiles: '',
          material: '',
          projectId: '',
          customerName: '',
          projectName: '',
          imgFiles: '',
        },
        fileList: [],
        threeFileList: [],
        imgFileList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        // 表单中验证规则
        ruleForm: {
          drawingNumber: [
            { required: true, message: '请输入图纸代码', trigger: 'blur' },
          ],
          drawingName: [
            { required: true, message: '请输入图纸名称', trigger: 'blur' },
          ],
          productParentIdName: [
            { required: true, message: '请输入正确图纸代码', trigger: 'blur' },
          ],
          productChildIdName: [
            { required: true, message: '请输入正确图纸代码', trigger: 'blur' },
          ],
          drawingCategoryName: [
            { required: true, message: '请输入正确图纸代码', trigger: 'blur' },
          ],
          projectId: [{ required: true, message: '请选择工单号', trigger: 'change' },],
          customerName: [{ required: true, message: '请选择客户名称', trigger: 'change' },],
          projectName: [{ required: true, message: '请选择项目名称', trigger: 'change' },],
          attchFiles: [
            { validator: checkAttachFiles, required: true },
          ],
        },
        // excel信息展示
        alertBox: false,
        errorMsgList: [],
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          indexLabel: '序号',
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          menuAlign: 'center',
          align: 'center',
          column: [
            {
              label: "图纸编号",
              prop: "drawingNumber",
              width: 120,
            },
            {
              label: "图纸名称",
              prop: "drawingName",
              overHidden: true,
            },
            // {
            //   label: "工单号",
            //   prop: "workOrderNo",
            //   overHidden:true,
            // },
            // {
            //   label: "客户名称",
            //   prop: "customerName",
            //   overHidden:true,
            // },
            // {
            //   label: "项目名称",
            //   prop: "projectName",
            //   overHidden:true,
            // },
            {
              label: "操作人",
              prop: "userAccount",
            },
            {
              label: "上传时间",
              prop: "createTime",
              width: 140,
              format: "yyyy-MM-dd hh:mm:ss",
            },
            {
              label: "图纸状态",
              prop: "statusName",
            },

          ]
        },
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.drawinginfo_add, false),
          viewBtn: this.vaildData(this.permission.drawinginfo_view, false),
          delBtn: this.vaildData(this.permission.drawinginfo_delete, false),
          editBtn: this.vaildData(this.permission.drawinginfo_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      this.getOrderListFun();
    },
    watch: {
    },
    methods: {
      // select回调，判断当前下拉框是否展示
      handleChangeFlag(val) {
        this.projectEntity = [];
        // 保持原来的值
        let drawingNumber = this.attachForm.drawingNumber;
        let drawingName = this.attachForm.drawingName;
        let material = this.attachForm.material;
        getProjectById(val).then(res => {
          this.attachForm = res.data.data;
          this.attachForm.drawingNumber = drawingNumber;
          this.attachForm.drawingName = drawingName;
          this.attachForm.material = material;
        });
      },
      //图号修改后获取图纸类型
      drawingNumberChange() {
        getApplicationByNumber(this.attachForm.drawingNumber).then(res => {
          this.$set(this.attachForm, 'productChildIdName', res.data.data.productChildIdName);
          this.$set(this.attachForm, 'productParentIdName', res.data.data.productParentIdName);
          this.$set(this.attachForm, 'drawingCategoryName', res.data.data.drawingCategoryName);
        });
      },
      editChangeFlag(val) {
        this.projectEntity = [];
        // 保持原来的值
        let drawingNumber = this.attachForm.drawingNumber;
        let drawingName = this.attachForm.drawingName;
        let material = this.attachForm.material;
        let id = this.attachForm.id;
        getProjectById(val).then(res => {
          this.attachForm = res.data.data;
          this.attachForm.drawingNumber = drawingNumber;
          this.attachForm.drawingName = drawingName;
          this.attachForm.material = material;
          this.attachForm.id = id;
        });
      },

      // 上传图片的展开
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

      handleRemove(file, fileList) {
        console.log(file, fileList);
      },


      // 获取工单号得List
      getOrderListFun() {
        getOrderAllList().then((res) => {
          this.orderList = res.data.data;
        })
      },

      // 提交审批按钮
      handleApprove() {
        // this.$router.push('/wel');
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据审批?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return changeUploadStatus(this.ids);
        }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "提交成功!"
          });
          this.$refs.crud.toggleSelection();
        });
      },

      // 行内数据删除
      deleteExcel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          console.log("row---》" + row.id);
          return remove(row.id);
        }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
      },

      // 编辑状态移除文件
      editRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}?`).then(() => {
          this.fileList = fileList;
        });
      },

      // 编辑状态移除文件
      editRemoveThree(file, threeFileList) {
        return this.$confirm(`确定移除 ${file.name}?`).then(() => {
          this.threeFileList = threeFileList;
        });
      },

      // 编辑状态移除文件
      editRemoveImg(file, imgFileList) {
        return this.$confirm(`确定移除 ${file.name}?`).then(() => {
          this.imgFileList = imgFileList;
        });
      },
      // 自定义修改时上传事件
      editHttpRequest(file) {
        this.uploadForm.append('file', file.file);
      },


      uploadBefore() {
        this.fileList = [];
      },
      // 上传时变化
      uploadChange(file, fileList) {
        //截取文件名,自动识别图号与名称
        const name = this.attachForm.drawingName;
        if (typeof (name) == "undefined" || name == "") {
          const arrInfo = fileList[0].name.split("-");
          this.$set(this.attachForm, 'drawingNumber', arrInfo[0]);
          this.$set(this.attachForm, 'drawingName', arrInfo[1].split(".")[0]);
          this.drawingNumberChange();
        }
        let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
        if (existFile) {
          fileList.pop();
          this.$message({
            type: "warning",
            message: file.name + "文件已存在!"
          });
        }
        this.fileList = fileList;
      },

      // 修改附件信息回显
      editExcel(row) {
        let id = row.id;
        this.attachForm.id = id;
        getDetail(id).then(res => {
          this.attachForm = res.data.data;
          this.editBox = true;
        });
        this.fileList = [];
        this.threeFileList = [];
        this.imgFileList = [];
        // 图纸信息回显
        getPdfByUploadId(id).then((res) => {
          let attach = res.data.data;
          for (let i = 0; i < attach.length; i++) {
            this.fileList.push({ "url": attach[i].link, "name": attach[i].originalName });
          }
        });
        // 三维图纸信息
        getThreeByUploadId(id).then((res) => {
          let attach = res.data.data;
          for (let i = 0; i < attach.length; i++) {
            this.threeFileList.push({ "url": attach[i].link, "name": attach[i].originalName });
          }
        });
        // 获取图纸截图的展示信息
        getImgListByUploadId(id).then((res) => {
          let attach = res.data.data;
          for (let i = 0; i < attach.length; i++) {
            this.imgFileList.push({ "url": attach[i].link, "name": attach[i].originalName });
          }
        })

      },

      // 编辑状态提交成功
      editSuccess() {
        this.$refs.editFileUpload.clearFiles();
      },


      handleSuccess() {
        this.$refs.fileUpload.clearFiles();
      },
      // 修改页面信息提交
      editAttach(formName) {
        this.btnLoading=true;
        debugger
        // step1；删除之前存在的key
        this.uploadForm = new FormData();
        this.errorBox = false;
        this.errorList = [];
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.uploadForm.append("id", this.attachForm.id);
            this.uploadForm.append("drawingNumber", this.attachForm.drawingNumber);
            this.uploadForm.append("drawingName", this.attachForm.drawingName);
            this.uploadForm.append("material", this.attachForm.material);
            // this.uploadForm.append("projectId",this.attachForm.projectId);
            let len = this.$refs['editFileUpload'].$children[0].fileList.length;
            let len2 = this.$refs['editThreeUpload'].$children[0].fileList.length;
            let len3 = this.$refs['editImgUpload'].uploadFiles.length;

            let fileList = this.$refs['editFileUpload'].$children[0].fileList;
            let threeFileList = this.$refs['editThreeUpload'].$children[0].fileList;
            let imgFileList = this.$refs['editImgUpload'].uploadFiles;

            let bomResult = this.verifyBomXLS(fileList, this.attachForm.drawingNumber);
            if (bomResult.length) {
              this.errorBox = true;
              this.errorList = bomResult;
              return;
            }
            // 后台上传得报错信息
            let result = this.checkFile(fileList);
            if (result.length) {
              this.errorBox = true;
              this.errorList = result;
            }
            
            // 是否有重复的数据 文件数据  附件信息
            if (fileList.length) {
              for (let i = 0; i < fileList.length; i++) {
                if (fileList[i].status === "success") {
                  this.uploadForm.append('fileTypeList[' + i + '].fileName', fileList[i].name);
                  this.uploadForm.append('fileTypeList[' + i + '].status', fileList[i].status);
                  this.uploadForm.append('fileTypeList[' + i + '].type', "平面");
                  this.uploadForm.append('fileTypeList[' + i + '].url', fileList[i].url);
                }
              }
            }
            // 三维图纸信息
            if (threeFileList.length) {
              for (let i = 0; i < threeFileList.length; i++) {
                if (threeFileList[i].status === "success") {
                  this.uploadForm.append('threeFileTypeList[' + i + '].fileName', threeFileList[i].name);
                  this.uploadForm.append('threeFileTypeList[' + i + '].status', threeFileList[i].status);
                  this.uploadForm.append('threeFileTypeList[' + i + '].url', threeFileList[i].url);
                  this.uploadForm.append('threeFileTypeList[' + i + '].type', "三维");
                }
              }
            }

            // 图片信息
            if (imgFileList.length) {
              for (let i = 0; i < imgFileList.length; i++) {
                if (imgFileList[i].status === "success") {
                  this.uploadForm.append('fileImgTypeList[' + i + '].fileName', imgFileList[i].name);
                  this.uploadForm.append('fileImgTypeList[' + i + '].status', imgFileList[i].status);
                  this.uploadForm.append('fileImgTypeList[' + i + '].url', imgFileList[i].url);
                  this.uploadForm.append('fileImgTypeList[' + i + '].type', "图片");
                }
              }
            }

            // 验证数量 & 文件是否完整
            if (len && result.length === 0) {
              this.$refs.editFileUpload.submit();
              if (len2) {
                this.$refs.editThreeUpload.submit();
              }
              if (len3) {
                this.$refs.editImgUpload.submit();
              }
              this.fileList = fileList;
              debugger
              this.loading = true;
              this.$axios.post('/api/data-drawing-attach/drawingupload/updateExcel',
                this.uploadForm, { headers: { 'Content-type': 'multipart/form-data' } }).then((res) => {
                  console.log("res---->" + JSON.stringify(res.data.data))
                  if (res.data.data.error != null) {
                    if (res.data.data.error.length) {
                      this.errorBox = true;
                      for (let i = 0; i < res.data.data.error.length; i++) {
                        this.errorList.push(res.data.data.error[i]);
                      }
                    }
                  }
                  if (res.data.data.right != null) {
                    this.editBox = false;
                    this.onLoad(this.page);
                    this.$message({
                      type: "success",
                      message: "修改成功!"
                    });
                  }
                  this.loading = false;
                  this.btnLoading = false;
                });
            }

            // 测试环境中验证文件
            // if (len) {
            //   this.$refs.editFileUpload.submit();
            //   if (len2) {
            //     this.$refs.editThreeUpload.submit();
            //   }
            //   if (len3) {
            //     this.$refs.editImgUpload.submit();
            //   }
            // }

          }
        });
      },

      // 查看
      viewBtn(row) {
        let id = row.id;
        getDetail(id).then((res) => {
          this.attachForm = res.data.data;
        });
        this.fileList = [];
        this.threeFileList = [];
        this.imgFileList = [];
        // 图纸信息回显
        getPdfByUploadId(id).then((res) => {
          let attach = res.data.data;
          for (let i = 0; i < attach.length; i++) {
            this.fileList.push({ "url": attach[i].link, "name": attach[i].originalName });
          }
        });
        getThreeByUploadId(id).then((res) => {
          let attach = res.data.data;
          for (let i = 0; i < attach.length; i++) {
            this.threeFileList.push({ "url": attach[i].link, "name": attach[i].originalName });
          }
        });
        getImgListByUploadId(id).then((res) => {
          let attach = res.data.data;
          for (let i = 0; i < attach.length; i++) {
            this.imgFileList.push({ "url": attach[i].link, "name": attach[i].originalName });
          }
        })


        this.viewBox = true;

      },

      getBlob(url, cb) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = function () {
          if (xhr.status === 200) {
            cb(xhr.response);
          }
        };
        xhr.send();
      },
      saveAs(blob, filename) {
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, filename);
        } else {
          var link = document.createElement('a');
          var body = document.querySelector('body');

          link.href = window.URL.createObjectURL(blob);
          link.download = filename;

          // fix Firefox
          link.style.display = 'none';
          body.appendChild(link);

          link.click();
          body.removeChild(link);

          window.URL.revokeObjectURL(link.href);
        }
      },
      download(url, filename) {
        let that = this;
        this.getBlob(url, function (blob) {
          that.saveAs(blob, filename);
        });
      },

      handlePreview(file) {
        // this.download(file.url, file.name);
        document.location.href = file.url
      },

      // 上传按钮事件
      handleUpload() {
        this.attachBox = true;
        this.attachForm = {};
        this.fileList = [];
        this.threeFileList = [];
        this.errorList = [];
      },

      // 指定文件的url地址 pdf dwg xls xlsx
      beforeUpload(file) {
        this.uploadForm.append("file", file.file);
      },
      // 三维图纸上传
      threrBeforeUpload(file) {
        this.uploadForm.append("threeFile", file.file);
      },
      imgBeforeUpload(file) {
        this.uploadForm.append("imgFile", file.file);
      },

      // 数组中元素出现得个数
      checkNum(arr) {
        return arr.reduce(function (prev, next) {
          prev[next] = (prev[next] + 1) || 1;
          return prev;
        }, {});
      },
      // 检查上传得文件得附件信息是否完整
      checkFile(array) {
        let nameArray = new Array();
        for (let i = 0; i < array.length; i++) {
          let name = array[i].name.substring(0, 13);
          nameArray.push(name);
        }
        // 名称存在得个数
        let arr = this.checkNum(nameArray);
        // 返回值
        let returnValue = new Array();
        for (let i = 0; i < nameArray.length; i++) {
          if (arr[nameArray[i]] <= 1) {
            returnValue.push(nameArray[i] + "缺少其他附件资料");
          }
        }
        return returnValue;
      },

      //修改附件时检验图号的bom.xls文件是否存在
      verifyBomXLS(array, drawingNumber) {
        let nameFlag = 0;
        let nameArray = new Array();
        for (let i = 0; i < array.length; i++) {
          if("xls" === array[i].name.split('.').pop().toLowerCase() || "xlsx" === array[i].name.split('.').pop().toLowerCase()){
          let name = array[i].name.substring(0, 13);
          nameArray.push(name);
          }
          
        }
        nameArray.forEach(name => {
          nameFlag += (name == drawingNumber ? 1 : 0);
        });
        let result = new Array();
        if(nameFlag === 0){
          result.push(drawingNumber + "缺失文件Bom表")
        }
        return result;
      },

      // 检查重复文件
      checkDistinctFile(array) {
        let nameArray = new Array();
        for (let i = 0; i < array.length; i++) {
          let name = array[i].name;
          nameArray.push(name);
        }
        let arr = this.checkNum(nameArray);
        // 返回值
        let returnValue = new Array();
        for (let i = 0; i < nameArray.length; i++) {
          if (arr[nameArray[i]] <= 1) {
            returnValue.push(nameArray[i] + "文件重复上传");
          }
        }
        return returnValue;
      },


      // 检查上传得附件 对应得图号信息，是否在数据库中已经存在
      // checkDbFile(array){
      //
      // },

      // 提交附件信息
      submitAttach(formName) {
        
        this.errorList = [];
        // 删除之前的key
        this.uploadForm = new FormData();
        debugger
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.uploadForm = new FormData();
            // 图纸编号
            this.uploadForm.append("drawingNumber", this.attachForm.drawingNumber);
            // 图纸名称
            this.uploadForm.append("drawingName", this.attachForm.drawingName);
            debugger
            // 材料
            this.uploadForm.append("material", (typeof (this.attachForm.material) == "undefined") ? "" : this.attachForm.material);
            // this.uploadForm.append("projectId",this.attachForm.projectId);
            // 附件文件列表
            let len = this.$refs['fileUpload'].$children[0].fileList.length;
            // 三维图纸列表
            let len2 = this.$refs['threeUpload'].$children[0].fileList.length;
            // 图片缩略图
            let len3 = this.$refs['imgUpload'].uploadFiles.length;

            let fileList = this.$refs['fileUpload'].$children[0].fileList;

            // 后台上传得报错信息

            let result = this.checkFile(fileList);
            if (result.length) {
              this.errorBox = true;
              this.errorList = result;
            }
            // 验证数量 & 文件是否完整
            if (len > 0 & result.length === 0) {
              this.$refs.fileUpload.submit();
              if (len2) {
                this.$refs.threeUpload.submit();
              }
              if (len3) {
                this.$refs.imgUpload.submit();
              }
            } else {
              result.forEach(element => this.$message.warning(element));
              return;
            }
            this.fileList = fileList;
              this.btnLoading = true;
              this.loading = true;
              this.$axios.post('/api/data-drawing-attach/drawingupload/updateExcel',
                this.uploadForm, { headers: { 'Content-type': 'multipart/form-data' } }).then((res) => {
                  if (res.data.data.error != null) {
                    if (res.data.data.error.length) {
                      this.errorBox = true;
                      for (let i = 0; i < res.data.data.error.length; i++) {
                        this.errorList.push(res.data.data.error[i]);
                      }
                      this.loading = false;
                      this.btnLoading = false;
                    }
                  }
                  if (res.data.data.right != null) {
                    debugger
                    this.attachBox = false;
                    this.onLoad(this.page);
                    this.$message({
                      type: "success",
                      message: "上传成功!"
                    });
                  }
                  // this.loading = false;
                  this.btnLoading = false;
                });
          }
        });
      },

      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      // 行内数据删除
      rowDel(row) {
        console.log("id------>" + row.id);
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      // 批量删除
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => { return remove(this.ids); }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }

    }

  }
</script>

<style scoped>
  el-select {
    width: 100%;
  }
</style>